package com.rlyy.rsj.job.statistic;

import com.rlyy.rsj.common.JobConstans;
import com.rlyy.rsj.job.DoUpBilJob;
import com.rlyy.rsj.job.IScheduler;
import com.rlyy.rsj.utils.DistributeLock;
import com.rlyy.rsj.utils.RedisKeyFactory;
import common.util.DateTimeFormatterUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;

import static com.rlyy.rsj.utils.DistributeLock.oneMinute;

/**
 * 定时统计测试环境产品使用情况
 *
 * @author yuanqinglong
 * @since 2021/3/9 18:09
 */
@Deprecated
@Component
public class StatisticTestUsage implements IStatisticUsageJob, IScheduler {

    private static final String LOCK_KEY = RedisKeyFactory.wrapJobKey(StatisticTestUsage.class.getName());

    @Override
//    @Scheduled(cron = "0 30 0 * * ?")
    public void scheduler() {
        try {
            String result = DistributeLock.get(LOCK_KEY);
            if (StringUtils.isBlank(result)) {
                DistributeLock.lock(LOCK_KEY, DateTimeFormatterUtil.dateTimeToString(LocalDateTime.now()), oneMinute);
                // 统计测试环境产品使用量定时任务
                LocalDate yesterday = LocalDate.now().minusDays(1);
                this.performStatistics(yesterday, JobConstans.TEST_ENVIRONMENT);
                logger.info("{}-统计测试环境-产品使用情况定时任务：执行时间:{}",LOCAL_INFO, DateTimeFormatterUtil.dateTimeToString(LocalDateTime.now()));
                DistributeLock.unlock(LOCK_KEY);
            } else {
                logger.warn("{}-未执行测试环境-产品使用情况定时任务",LOCAL_INFO);
            }
        } catch (Exception e) {
            logger.error("{}-定时统计测试环境产品使用情况启动失败 !",LOCAL_INFO, e);
            throw new RuntimeException("定时统计测试环境产品使用情况 启动失败 !", e);
        }
    }


    /**
     * 统计产品使用量SQL语句
     *
     * @param statisticsDate 统计日期
     * @param orgId          统计机构id（如果传递机构id 则是手动触发此机构的统计 、未传递机构id统计指定统计日期的所有机构的使用情况）
     * @return SQL
     */
    @Override
    public String statisticalSqlStatement(LocalDate statisticsDate, String orgId) {
        String orgCondition = StringUtils.isBlank(orgId) ? "" : " AND org_id = '" + orgId + "'";
        String dateZone = "(log_storagetime < '" + statisticsDate.plusDays(1) + "' AND log_storagetime >= '"+ statisticsDate+"')";
        return  " SELECT log_prod_uid ,prod_name ,COUNT(*) AS stat_useamount, " +
                " log_orgp_id,org_id,org_sname,log_storagetime::DATE as log_storagetime " +
                " FROM sys.oper_test_log LEFT JOIN sys.sys_prod ON prod_uid = log_prod_uid " +
                " LEFT JOIN sys.sys_orgp orgp ON orgp.orgp_id =log_orgp_id LEFT JOIN sys.sys_org ON org_id = orgp.orgp_org_id " +
                " WHERE  log_iscost ='" + JobConstans.IS_COST + "' AND " + dateZone + orgCondition +
                " GROUP BY log_orgp_id,log_prod_uid,prod_name,org_id,org_sname,log_storagetime::DATE; ";
    }
}
